import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/pages/main/cycling_record_detail/state.dart';
import 'package:inmotion_pro/service/global_service.dart';

class CyclingRecordListController extends GetxController {
  final CyclingRecordDetailState state = CyclingRecordDetailState();

  late final Worker _yearWorker;
  late final Worker _monthWorker;

  int _page = 1;
  final int _pageSize = 10;

  @override
  void onInit() {
    super.onInit();

    Future.delayed(const Duration(milliseconds: 300), () {
      refreshCyclingRecords();
    });

    // 监听年份/月份变化
    _yearWorker = ever(state.currentYear, (value) {
      refreshCyclingRecords();
    });
    _monthWorker = ever(state.currentMonth, (value) {
      refreshCyclingRecords();
    });
  }

  @override
  void onClose() {
    _yearWorker.dispose();
    _monthWorker.dispose();
    super.onClose();
  }

  // 下拉刷新
  Future<void> refreshCyclingRecords() async {
    _page = 1;
    state.hasMore.value = true;
    await getCyclingRecords(isRefresh: true);
  }

  // 上拉加载更多
  Future<void> loadMoreCyclingRecords() async {
    if (!state.hasMore.value) return;
    _page++;
    await getCyclingRecords();
  }

  // 获取服务端骑行记录
  Future<void> getCyclingRecords({bool isRefresh = false}) async {
    await ApiHelper()
        .getCyclingRecords(GlobalService.to.currentVehicleModel.value.sn,
            year: state.currentYear.value == 0 ? null : state.currentYear.value,
            month:
                state.currentMonth.value == 0 ? null : state.currentMonth.value,
            page: _page,
            pageSize: _pageSize)
        .then((rsp) {
      if (isRefresh) {
        debugPrint("🚴‍♂️ 获取到 ${rsp.ridingRecords} 条骑行记录");
        state.cyclingRecords.value = rsp.ridingRecords;
      } else {
        debugPrint("🚴‍♂️ 获取到更多 ${rsp.ridingRecords.length} 条骑行记录");
        state.cyclingRecords.addAll(rsp.ridingRecords);
      }
      state.rideRecordStats.value = rsp.rideRecordStats;
      state.hasMore.value = rsp.totalCount > state.cyclingRecords.length;
    }).catchErrorHandler();
  }
}
